package serializer;

import com.google.protobuf.InvalidProtocolBufferException;

import domain.SensorData;
import proto.Proto;

public class ProtobufSerializer implements ISerializer {

	public SensorData decode(byte[] buf) {
		try {
			Proto.SensorData.parseFrom(buf);
			Proto.SensorData sensorData = Proto.SensorData.parseFrom(buf);
			SensorData s = new SensorData();
			s.setLatitude(sensorData.getLatitude());
			s.setLongitude(sensorData.getLongitude());
			s.setElevation(sensorData.getElevation());
			s.setTemperature(sensorData.getTemperature());
			return s;
		} catch (InvalidProtocolBufferException e) {
			System.err.println("Can't deserialize protobuf object. Details: "
					+ e.getMessage());
			return null;
		}

	}

	public byte[] encode(SensorData obj) {
		Proto.SensorData sensorData = Proto.SensorData.newBuilder()
				.setLatitude(obj.getLatitude())
				.setLongitude(obj.getLongitude())
				.setElevation(obj.getElevation())
				.setTemperature(obj.getTemperature()).build();

		return sensorData.toByteArray();
	}
}
